package com.pro.staffmanage.controller;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.MediaType;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class StaticResourceController {

    private final Producer kaptchaProducer;

    public StaticResourceController(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    @GetMapping("/verify.jpeg")
    public void generateKaptchaVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        String text = kaptchaProducer.createText();
        //  传验证码, 最好换成Redis
        session.setAttribute("verifyCode", text);
        //  生成图片放验证码
        BufferedImage image = kaptchaProducer.createImage(text);
        //  ImageIO可将图片写入response请求体中, 前端img元素访问时可直接显示
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }

    @GetMapping("/verify.png")
    public String generateKaptchaVerifyCodeSeparate(HttpServletResponse response, HttpSession session) throws IOException {
        String text = kaptchaProducer.createText();
        //  传验证码, 最好换成Redis
        session.setAttribute("verifyCode", text);
        //  生成图片放验证码
        BufferedImage image = kaptchaProducer.createImage(text);
        //  ImageIO可将图片写入response请求体中, 前端img元素访问时可直接显示
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(image, "png", fos);
        return Base64.encodeBase64String(fos.toByteArray());
    }

}
